const _ = require('lodash')

const OptionStore = require('optionStore')

const Schema = class {

	constructor () {
		this.data = _.cloneDeep(require('./schema.js'))

		this.iterOption(option => {
			option.value = ''
			option.suggest = new OptionStore(option.name)
		})
	}

	iterOption (func) {
		for (const type in this.data) {
			if (this.data[type].disable !== true) {
				for (const option of this.data[type]) {
					func(option)
				}
			}
		}
	}

	removeOption (name) {
		for (const type in this.data) {
			this.data[type] = this.data[type].filter(x => x.name !== name)
		}
	}

	removeTab (name) {
		const type = this.data[name]

		if (type) {
			type.disable = true
		}
	}

	save () {
		this.iterOption(option => {
			option.suggest.add(option.value).save()
		})
	}

}


module.exports = {
	mixins: [
		require('mixin/rpc'),
	],
	data () {
		return {
			page       : 'Basic',
			predata    : [],
			disableTabs: [],
			schema     : new Schema(),
			focusForm  : '',
		}
	},
	computed: {
		options: {
			get () {
				const result = {}

				this.schema.iterOption(({ name, value }) => {
					const v = _.trim(value)

					if (v) {
						result[name] = v
					}
				})

				return result
			},
		},
	},
	ready () {
		for (const name of this.disableOptions) {
			this.schema.removeOption(name)
		}

		for (const name of this.disableTabs) {
			this.schema.removeTab(name)
		}

		if (['add', 'setting.global'].includes(this.$route.name)) {
			this.predata.push(
				this.getGlobalOption().then(options => {
					this.schema.iterOption(option => {
						option.value = options[option.name]
					})
				})
			)
		}
	},
}